//
//  MCChooseAreaViewController.swift
//  StoreManage
//
//  Created by MC on 2018/9/20.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

typealias MCChooseAreaViewControllerClosure = (NSArray) -> Void

class MCChooseAreaViewController: MCViewController {
    
    
    public var selectedArray = [MCChooseAreaModel]()
    
    var closure : MCChooseAreaViewControllerClosure?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        closureManager()
        
        sendNetworking()
    }
    
    // MARK: - Setter & Getter
    lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()

    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var lettersArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var citysView: MCChooseCitysView = {
        let view = MCChooseCitysView()
        return view
    }()
}

//MARK: 通知回调，闭包回调，点击事件
extension MCChooseAreaViewController {
    func closureManager() {
        self.citysView.closure = { models,indexPath in
            
            
            
            let array = self.dataArrayM[indexPath.section] as? NSArray ?? []
            
            let model = array[indexPath.row] as! MCChooseAreaModel
            
            model.selectedCityModels = models
            
            self.tableView.reloadData()
        }
    }
    
    @objc func rightItemClicked() {
        // 数据处理，获得省为单位的数组数据
        let array = processTheData(array: dataArrayM)
        closure?(array)
        navigationController?.popViewController(animated: true)
    }
}


//MARK: 网络请求
extension MCChooseAreaViewController {
    
    func sendNetworking() {
        
        MCNetwork.POST(JAVA_getProvinceCityAreaByOrder, vc: self, success: { (data) in
            
            let dataArray = data.arrayObject ?? []
            
            for item in dataArray {
                
                let itemDict = item as? Dictionary<String,Any> ?? [:]

                let number = itemDict["number"] as? String ?? ""
                self.lettersArrayM.add(number)
                
                let provinceArrayM = NSMutableArray()
                let list = itemDict["list"] as? NSArray ?? []
                for province in list {
                    let provinceDict = province as? Dictionary<String,Any> ?? [:]
                                    
                    let model = MCChooseAreaModel()
                    model.setValuesForKeys(provinceDict)
                    
                    
                    for selectedModel in self.selectedArray {
                        if model.proId == selectedModel.proId {
                            model.selectedCityModels = selectedModel.allCityModels
                            model.b = true
                        }
                    }
                    
                    provinceArrayM.add(model)
                }
                
                self.dataArrayM.add(provinceArrayM)
            }
            
            
        
            
            
            self.tableView.reloadData()
            
        }, failure: nil)
    }
}

//MARK: UI的处理,通知的接收
extension MCChooseAreaViewController {
    
    func baseSetting() {
        self.title = "选择区域"
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("保存", target: self, selector: #selector(rightItemClicked))
    }
    
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
    }
    
    // 将选中的以字母排序的数据 转为 省为单位的数组
    func processTheData(array:NSArray) -> NSArray {
        
        let arrayM = NSMutableArray()
        for item in array {
            let itemArray = item as! NSArray
            
            for model in itemArray {
                let provinceModel = model as! MCChooseAreaModel
                if provinceModel.b {
                    arrayM.add(provinceModel)
                }
            }
        }
        
        
        return arrayM
    }
}

extension MCChooseAreaViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = dataArrayM[section] as? NSArray ?? []
        return array.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let array = dataArrayM[indexPath.section] as? NSArray ?? []
        let model = array[indexPath.row] as! MCChooseAreaModel


        return model.selectedCitysHeight
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel()
        label.font = MCFont(13)
        label.textColor = UIColor.MCBlack
        label.backgroundColor = UIColor.MCGray_light
        label.text = "      \(lettersArrayM[section])"
        return label
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return lettersArrayM as? [String]
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return index
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
                
        let cell = MCChooseAreaCell.customCell(tableView: tableView)
        
        
        let array = dataArrayM[indexPath.section] as? NSArray ?? []
        
        let model = array[indexPath.row] as! MCChooseAreaModel
        
        cell.model = model
        
        cell.closure = { model in

            // 未选中，弹出选择框
            if model.selectedCityModels.count == 0 {
                self.citysView.indexPath = indexPath
                self.citysView.model = model
                self.view.window?.addSubview(self.citysView)
                self.citysView.snp.remakeConstraints { (make) ->Void in
                    make.edges.equalTo(self.view.window!)
                }
            } else {
                cell.statusButton.isSelected = !cell.statusButton.isSelected
                model.selectedCityModels = [MCChooseAreaCityModel]()
                self.tableView.reloadData()
            }
            

        }
        
        return cell
    }
}
